import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

public class Menu {
    private BillManager billManager;
    private Scanner scanner;

    public Menu(BillManager billManager) {
        this.billManager = billManager;
        this.scanner = new Scanner(System.in);
    }

    public void showMenu() {
        while (true) {
            System.out.println("个人账单管理系统菜单：");
            System.out.println("1. 记录收入");
            System.out.println("2. 记录支出");
            System.out.println("3. 设置每月预算");
            System.out.println("4. 展示所有账单记录");
            System.out.println("5. 查询账单记录");
            System.out.println("6. 查看月度统计信息");
            System.out.println("7. 退出");
            System.out.print("请输入菜单选项序号：");
            try {
                int choice = scanner.nextInt();
                switch (choice) {
                    case 1:
                        recordIncome();
                        break;
                    case 2:
                        recordExpense();
                        break;
                    case 3:
                        setMonthlyBudget();
                        break;
                    case 4:
                        billManager.displayBills();
                        break;
                    case 5:
                        queryBills();
                        break;
                    case 6:
                        showMonthlyStatistics();
                        break;
                    case 7:
                        System.out.println("感谢使用，已退出程序！");
                        System.exit(0);
                    default:
                        System.out.println("无效的选项，请重新输入。");
                }
            } catch (Exception e) {
                System.out.println("输入格式错误，请重新输入。");
                scanner.nextLine();  // 清除输入缓冲区的错误输入
            }
        }
    }

    private void recordIncome() {
        try {
            System.out.print("请输入收入日期（格式：yyyy-MM-dd）：");
            Date date = new SimpleDateFormat("yyyy-MM-dd").parse(scanner.next());
            System.out.print("请输入收入金额：");
            double amount = scanner.nextDouble();
            System.out.print("请输入收入类别：");
            String category = scanner.next();
            System.out.print("请输入备注：");
            String note = scanner.next();
            billManager.recordIncome(date, amount, category, note);
            System.out.println("收入记录成功！");
        } catch (ParseException | IllegalArgumentException e) {
            System.out.println("输入有误：" + e.getMessage());
        }
    }

    private void recordExpense() {
        try {
            System.out.print("请输入支出日期（格式：yyyy-MM-dd）：");
            Date date = new SimpleDateFormat("yyyy-MM-dd").parse(scanner.next());
            System.out.print("请输入支出金额：");
            double amount = scanner.nextDouble();
            System.out.print("请输入支出类别：");
            String category = scanner.next();
            System.out.print("请输入备注：");
            String note = scanner.next();
            billManager.recordExpense(date, amount, category, note);
            System.out.println("支出记录成功！");
        } catch (ParseException | IllegalArgumentException e) {
            System.out.println("输入有误：" + e.getMessage());
        }
    }

    private void setMonthlyBudget() {
        try {
            System.out.print("请输入月份（格式：yyyy-MM）：");
            String month = scanner.next();
            System.out.print("请输入预算金额：");
            double budget = scanner.nextDouble();
            billManager.setMonthlyBudget(month, budget);
            System.out.println("预算设置成功！");
        } catch (IllegalArgumentException e) {
            System.out.println("输入有误：" + e.getMessage());
        }
    }

    private void queryBills() {
        System.out.println("查询账单记录方式：");
        System.out.println("1. 按日期查询");
        System.out.println("2. 按日期范围查询");
        System.out.println("3. 按类别查询");
        System.out.print("请输入查询方式序号：");
        try {
            int queryChoice = scanner.nextInt();
            switch (queryChoice) {
                case 1:
                    queryByDate();
                    break;
                case 2:
                    queryByDateRange();
                    break;
                case 3:
                    queryByCategory();
                    break;
                default:
                    System.out.println("无效的查询方式选项，请重新输入。");
            }
        } catch (Exception e) {
            System.out.println("输入格式错误，请重新输入。");
            scanner.nextLine();
        }
    }

    private void queryByDate() {
        try {
            System.out.print("请输入查询日期（格式：yyyy-MM-dd）：");
            Date date = new SimpleDateFormat("yyyy-MM-dd").parse(scanner.next());
            System.out.println("收入记录：");
            billManager.queryIncomeByDate(date).forEach(record -> {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                System.out.println("日期：" + dateFormat.format(record.getDate()) +
                        ", 金额：" + record.getAmount() +
                        ", 类别：" + record.getCategory() +
                        ", 备注：" + record.getNote());
            });
            System.out.println("支出记录：");
            billManager.queryExpenseByDate(date).forEach(record -> {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                System.out.println("日期：" + dateFormat.format(record.getDate()) +
                        ", 金额：" + Math.abs(record.getAmount()) +
                        ", 类别：" + record.getCategory() +
                        ", 备注：" + record.getNote());
            });
        } catch (ParseException e) {
            System.out.println("日期格式输入错误，请重新输入。");
        }
    }

    private void queryByDateRange() {
        try {
            System.out.print("请输入起始日期（格式：yyyy-MM-dd）：");
            Date startDate = new SimpleDateFormat("yyyy-MM-dd").parse(scanner.next());
            System.out.print("请输入结束日期（格式：yyyy-MM-dd）：");
            Date endDate = new SimpleDateFormat("yyyy-MM-dd").parse(scanner.next());
            System.out.println("收入记录：");
            billManager.queryIncomeByDateRange(startDate, endDate).forEach(record -> {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                System.out.println("日期：" + dateFormat.format(record.getDate()) +
                        ", 金额：" + record.getAmount() +
                        ", 类别：" + record.getCategory() +
                        ", 备注：" + record.getNote());
            });
            System.out.println("支出记录：");
            billManager.queryExpenseByDateRange(startDate, endDate).forEach(record -> {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                System.out.println("日期：" + dateFormat.format(record.getDate()) +
                        ", 金额：" + Math.abs(record.getAmount()) +
                        ", 类别：" + record.getCategory() +
                        ", 备注：" + record.getNote());
            });
        } catch (ParseException e) {
            System.out.println("日期格式输入错误，请重新输入。");
        }
    }

    private void queryByCategory() {
        System.out.print("请输入查询类别：");
        String category = scanner.next();
        System.out.println("收入记录：");
        billManager.queryIncomeByCategory(category).forEach(record -> {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            System.out.println("日期：" + dateFormat.format(record.getDate()) +
                    ", 金额：" + record.getAmount() +
                    ", 类别：" + record.getCategory() +
                    ", 备注：" + record.getNote());
        });
        System.out.println("支出记录：");
        billManager.queryExpenseByCategory(category).forEach(record -> {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            System.out.println("日期：" + dateFormat.format(record.getDate()) +
                    ", 金额：" + Math.abs(record.getAmount()) +
                    ", 类别：" + record.getCategory() +
                    ", 备注：" + record.getNote());
        });
    }

    private void showMonthlyStatistics() {
        System.out.print("请输入要查看统计信息的月份（格式：yyyy-MM）：");
        String month = scanner.next();
        System.out.println("该月总收入：" + billManager.calculateTotalIncomeForMonth(month));
        System.out.println("该月总支出：" + billManager.calculateTotalExpenseForMonth(month));
        System.out.println("该月各类别金额：");
        billManager.calculateCategoryAmountsForMonth(month).forEach((key, value) -> {
            System.out.println(key.split("-")[1] + "：" + value);
        });
        System.out.println("该月剩余预算：" + billManager.getRemainingBudget(month));
    }
}